package org.budo.support.java.regex.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.budo.support.java.regex.pattern.factory.RegexPatternFactory;

/**
 * @author lmw
 */
public class RegexUtil {
    public static String collect(String regex, String input) {
        Matcher matcher = getPattern(regex).matcher(input);
        while (matcher.find()) {
            return matcher.group(0);
        }
        return "";
    }

    private static Pattern getPattern(String regex) {
        RegexPatternFactory regexPatternFactory = RegexPatternFactory.getInstance();
        return regexPatternFactory.getPattern(regex);
    }

    public static Matcher matcher(String regex, String input) {
        Pattern pattern = getPattern(regex);
        return pattern.matcher(input);
    }

    public static Boolean matches(String regex, String input) {
        Matcher matcher = matcher(regex, input);

        return matcher.matches();
    }

    public static Boolean matches(Pattern pattern, String input) {
        if (null == pattern || null == input) {
            return false;
        }

        Matcher matcher = pattern.matcher(input);
        return matcher.matches();
    }

    public static String replaceAll(String regex, String input, String replacement) {
        Matcher matcher = matcher(regex, input);

        return matcher.replaceAll(replacement);
    }
}